package middleware

import (
	"github.com/cn-ygf/go-admin/internal/modular/system/service"
	"github.com/kataras/iris/v12"
	"strings"
)

func responseAccessDenied(ctx iris.Context) {
	r := map[string]any{
		"code": 401,
		"msg":  "未授权访问",
	}
	ctx.StopWithJSON(200, r)
}

// Auth 身份验证中间件
func Auth(ctx iris.Context) {
	token := ctx.GetHeader("Authorization")
	if token != "" {
		token = strings.Replace(token, "Bearer ", "", 1)
		user, err := service.LoginService.VerifyToken(token)
		if err != nil {
			responseAccessDenied(ctx)
			return
		}
		ctx.Values().Set("user", user)
		ctx.Next()
		return
	}
	responseAccessDenied(ctx)
}
